/*    file: RtpDumpReader.cpp
 *    desc:
 * 
 * created: 2014-07-21 15:21:48
 *  author: zhengchuanjiang
 * company: 
 */

#include "stdafx.h"
#include "RtpDumpReader.h"
#include <assert.h>

static const char* RTP_DUMP_PREFIX = "#!rtpplay1.0";
static const int FILE_HEADER_SIZE = 128;



RtpDumpReader::RtpDumpReader():
    m_file()
{

}

RtpDumpReader::~RtpDumpReader()
{
    close();
}

bool RtpDumpReader::open(const char* filename)
{
    //m_file = fopen(filename, "rb");
    fopen_s(&m_file, filename, "rb");

    if (!checkFileFormat())
    {
        fclose(m_file);
        m_file = NULL;
    }
    return (m_file != NULL);
}

bool RtpDumpReader::isOpen()
{
    return (m_file != NULL);
}

void RtpDumpReader::close()
{
    if (m_file)
    {
        fclose(m_file);
        m_file = NULL;
    }
}

bool RtpDumpReader::read(RtpDumpReader::Packet& pkt)
{
    RD_packet_t packet;
    size_t length = fread(&packet, 1, sizeof(packet), m_file);
    if (length != sizeof(packet))
    {
        return false;
    }

    packet.length = ntohs(packet.length);
    assert(packet.plen != 0);

    size_t pktSize = packet.length - sizeof(packet);
    m_buffer.ensure(pktSize);
    pkt.length = fread(m_buffer.data(), 1, pktSize, m_file);
    pkt.ptr = m_buffer.data();

    return (pktSize == pkt.length);
}

bool RtpDumpReader::checkFileFormat()
{
    char fileHdr[FILE_HEADER_SIZE];
    size_t length = fread(fileHdr, 1, FILE_HEADER_SIZE, m_file);
    size_t hdrSize = 0;
    for (size_t i = 0; i < length; i ++)
    {
        if (fileHdr[i] == '\n')
        {
            hdrSize = i+1;
            break;
        }
    }

    if (hdrSize == 0)
    {
        return false;
    }

    fseek(m_file, hdrSize, SEEK_SET);

    RD_hdr_t hdr;
    length = fread(&hdr, 1, sizeof(hdr), m_file);
    if (length != sizeof(hdr))
    {
        return false;
    }

    return TRUE;
}
